// 配置
var apiUrl;
var wsUrl;

function removeTrailingSlash(url) {
    return url.replace(/\/$/, '');
}

function getServerUrl(){
    const protocol = window.location.protocol;
    const hostname = window.location.hostname;
    const port = window.location.port;
    return `${protocol}//${hostname}${port ? ':' + port : ''}`;
} 

function initUrl() {
    apiUrl = localStorage.getItem("apiUrl") || getServerUrl();
    apiUrl = removeTrailingSlash(apiUrl);
    if (apiUrl.startsWith('https://')) {
        wsUrl = apiUrl.replace('https://', 'wss://');
    } else if (apiUrl.startsWith('http://')) {
        wsUrl = apiUrl.replace('http://', 'ws://');
    } else {
        wsUrl = `ws://localhost:5000`;
    }

    // 发送消息给content script
    if (chrome.tabs) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            chrome.tabs.sendMessage(tabs[0].id, { apiUrl: apiUrl }, function (response) {

            });
        });
    }

}

initUrl();

document.querySelector('.server-url').value = apiUrl;



var timeoutIndex;
document.querySelector('.server-url').addEventListener('input', (event) => {
    var val = event.target.value;
    if (timeoutIndex) {
        clearTimeout(timeoutIndex)
        timeoutIndex = null
    }
    timeoutIndex = setTimeout(() => {
        localStorage.setItem("apiUrl", val);
        initUrl()
    }, 1000)

})



// 正在下载
const btns = document.querySelectorAll('.left ul li');

btns.forEach(btn => {
    btn.addEventListener('click', function (event) {
        if (!event.target.classList.contains('activate')) {
            document.querySelector('.activate').classList.remove('activate');
            event.target.classList.add('activate');

            const pe = event.target.parentElement;
            const children = pe.children;
            const index = Array.prototype.indexOf.call(children, event.target) + 1;


            document.querySelector('.sub-activate').classList.remove('sub-activate');
            document.querySelector('.right div:nth-child(' + index + ')').classList.add('sub-activate');

        }
    });
});




fetch(`${apiUrl}/downloading`)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        if (data.code == 0) {
            var html = '';
            for (var i = 0; i < data.data.length; i++) {
                var d = data.data[i];
                html += getTemplate({ apiUrl: apiUrl, uid: d.uid, fileName: d.fileName, prog: d.prog, size: d.size, speed: d.speed }, 'downloading-template');
            }
            document.querySelector('.downloading .list').innerHTML = html;

        }

        document.querySelector('.sreach-top').classList.remove('loading');
    })
    .catch(error => {
        console.error('Error:', error);
        document.querySelector('.sreach-top').classList.remove('loading');
    });



// 下载完成
fetch(`${apiUrl}/downloaded`)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        if (data.code == 0) {
            var html = '';
            for (var i = 0; i < data.data.length; i++) {
                var d = data.data[i];
                html += getTemplate({ apiUrl: apiUrl, uid: d.uid, fileName: d.fileName, size: d.size }, 'downloaded-template');
            }
            document.querySelector('.downloaded .list').innerHTML = html;
        }

        document.querySelector('.sreach-top').classList.remove('loading');
    })
    .catch(error => {
        console.error('Error:', error);
        document.querySelector('.sreach-top').classList.remove('loading');
    });

document.querySelectorAll('.list').forEach(elem => {
    elem.addEventListener('click', (event) => {
        var target = event.target;
        if (target.classList.contains('file-delete')) {
            var fileName = target.parentNode.getAttribute('fileName')
            del(fileName);
        } else if (target.classList.contains('file-cancel')) {
            var fileName = target.parentNode.getAttribute('fileName')
            cancel(fileName);
        }
    })
    elem.addEventListener('dblclick', (event) => {
        var target = event.target;
        if (target.classList.contains('file-image')) {
            openLargeImage(event)
        }
    })
});

document.querySelector('.sreach-img').addEventListener('dblclick', (event) => {
    openLargeImage(event);
})

document.querySelector('.sreach-img').addEventListener('error', (event) => {
    var target = event.target;
    setTimeout(() => { target.src = target.src + '?' + new Date().getTime(); }, 2000);
})


document.getElementById('modal').addEventListener('click', (event) => {
    closeModal();
});

//搜索
var sreachUrl = '';
document.querySelector('.sreach-btn').addEventListener('click', (event) => {


    const url = document.querySelector('.sreach-text').value;

    if (url) {

        sreachUrl = url.replace("youtube", 'baidu')

        document.querySelector('.sreach-top').classList.add('loading');

        fetch(`${apiUrl}/download?url=${encodeURIComponent(sreachUrl)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.code == 0) {
                    var html = '';
                    for (var i = 0; i < data.data.length; i++) {
                        var d = data.data[i];
                        const sd = JSON.stringify(d);
                        if (d.ch) {
                            html += `<option value='${sd}'>[视频+音频${d.resolution}.${d.ext}]</option>`;
                        } else if (d.resolution == 'audio') {
                            html += `<option value='${sd}'>[音频.${d.ext}]</option>`;
                        } else {
                            html += `<option value='${sd}'>[视频${d.resolution}.${d.ext}]</option>`;
                        }

                        if (i == 0) {
                            document.querySelector('.sreach-img').src = `${apiUrl}/download/${d.uid}.webp`;
                        }

                    }
                    document.querySelector('.download-select').innerHTML = html;


                }

                document.querySelector('.sreach-top').classList.remove('loading');
            })
            .catch(error => {
                console.error('Error:', error);
                document.querySelector('.sreach-top').classList.remove('loading');
            });
    }
});

document.querySelector('.download-btn').addEventListener('click', (event) => {

    const sd = document.querySelector('.download-select').value;

    if (sd) {

        var json = JSON.parse(sd);

        const data = {
            url: sreachUrl,
            formatId: json.id,
            uid: json.uid,
            ext: json.ext,
            resolution: json.resolution
        };

        fetch(`${apiUrl}/download`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

});

function openLargeImage(event) {
    const src = event.target.src
    document.getElementById('modalImage').src = src;
    document.getElementById('modal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('modal').style.display = 'none';
}

function cancel(fileName) {
    console.log('cancel')
    fetch(`${apiUrl}/cancel?fileName=${fileName}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            if (data.code == 0) {
                document.querySelector('li[fileName="' + fileName + '"]').remove();
            }

        })
        .catch(error => {
            console.error('Error:', error);
        });
}

function del(fileName) {
    console.log('del')
    fetch(`${apiUrl}/delete?fileName=${fileName}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            if (data.code == 0) {
                document.querySelector('li[fileName="' + fileName + '"]').remove();
            }

        })
        .catch(error => {
            console.error('Error:', error);
        });
}


function getTemplate(json, id) {

    const template = document.getElementById(id);
    let content = template.innerHTML;

    for (let key in json) {
        if (json.hasOwnProperty(key)) {
            const regex = new RegExp(`{{${key}}}`, 'g');
            content = content.replace(regex, json[key]);
        }
    }


    return content;
}


function crateWs() {

    const socket = new WebSocket(wsUrl);
    socket.addEventListener('open', (event) => {
        console.log('Connected to WebSocket server');
    });

    socket.addEventListener('message', (event) => {
        console.log(event.data)
        const json = JSON.parse(event.data)
        if (json.status == 0) {
            const html = getTemplate({ apiUrl: apiUrl, uid: json.uid, fileName: json.fileName, prog: '', size: '', speed: '' }, 'downloading-template');

            document.querySelector('.downloading .list').innerHTML += html
        } else if (json.status == 1) {
            document.querySelector('li[fileName="' + json.fileName + '"] .file-prog').innerHTML = json.prog;
            document.querySelector('li[fileName="' + json.fileName + '"] .file-size').innerHTML = json.size;
            document.querySelector('li[fileName="' + json.fileName + '"] .file-speed').innerHTML = json.speed;
        } else if (json.status == 2) {
            console.log('li[fileName="' + json.fileName + '"]')
            document.querySelector('li[fileName="' + json.fileName + '"]').remove();
            const html = getTemplate({ apiUrl: apiUrl, uid: json.uid, fileName: json.fileName, size: json.size }, 'downloaded-template');
            document.querySelector('.downloaded .list').innerHTML += html
        }

    });

    socket.addEventListener('close', (event) => {
        console.log('Disconnected from WebSocket server');
    });

    socket.addEventListener('error', (event) => {
        console.error('WebSocket error:', event);
        setTimeout(() => crateWs(), 3000);
    });
}

crateWs();

